package com.ctcd.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ctcd.security.bean.Users;
import com.ctcd.security.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;



@Service("userDetailsService")
public class MyUserDetilsService implements UserDetailsService {

    //加载查询数据库的mapper
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //方法中可以查数据库，返回User，根据用户名查询
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        Users users = userMapper.selectOne(wrapper);

        System.out.println(users);
        //判断
        if(users ==null){
            throw new UsernameNotFoundException("用户名没有找到");
        }
        //不为空，将账号密码加入
        List<GrantedAuthority> auths=
                AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        //返回一个security提供的User 账号 密码 角色
        return new User(users.getUsername(),
                new BCryptPasswordEncoder().encode(users.getPassword()),auths);

    }
}
